package com.api.projects.service.impl;

import com.api.apicommon.model.entity.InterfaceInfo;
import com.api.projects.common.ErrorCode;
import com.api.projects.common.Params;
import com.api.projects.exception.BusinessException;
import com.api.projects.mapper.InterfaceInfoMapper;
import com.api.projects.service.InterfaceInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
    implements InterfaceInfoService{

    @Override
    public void validInterfaceInfo(InterfaceInfo interfaceInfo, boolean add) {
        //对添加的interfaceInfo信息进行校验，如果接口信息有问题就thorw出异常
    }

    /**
     * 校验请求参数的逻辑
     * @param standardRequestParams  标准的请求参数，从接口信息里面获取 [
     *          {"name":"username“，”type":"string"}
     *       ]
     * @param requestParams   请求参数  {"name":"张三"}
     * @param gson
     * @return
     */
    @Override
    public boolean validRequestParms(String standardRequestParams, String requestParams, Gson gson) {
        if(StringUtils.isAnyBlank(requestParams)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数不可为空");
        }
        Map<String,Object> map = null;
        //1.进行json转化
        try{
            map = gson.fromJson(requestParams, Map.class);
        }catch (Exception e){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR,"请求字符串有误，请检查后调用");
        }
        //2. 这里可以提前对输入的参数进行校验 逻辑：需要初始化一个需要参数的类含有data type 字符串，然后与map集合调用的参数进行对比
        Params[] params = gson.fromJson(standardRequestParams, Params[].class);
        List<Params> listParams = Arrays.asList(params);
        //3.进行比较
        for(Params param : listParams){
            if(map.get(param.getName()) == null){
                throw  new BusinessException(ErrorCode.PARAMS_ERROR,"缺少请求参数，请重试！");
            }
        }
        return true;
    }
}




